package org.example.DesignPatterns.Proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @description:
 * @author: farprt
 * @create: 2022-08-14 15:15
 **/
public class SimpleCGLibDemo {
    static class RealService{
        public void sayHello(){
            System.out.println("hello");
        }
    }

    static class SimpleInterceptor implements MethodInterceptor {
        @Override
        public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
            System.out.println("entering"+method.getName());
            Object result= methodProxy.invokeSuper(o,args);
            System.out.println("leaving"+method.getName());
            return result;
        }
    }

    public static <T> T getProxy(Class cls){
        Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(cls);
        enhancer.setCallback(new SimpleInterceptor());
        return (T) enhancer.create();
    }

    public static void main(String[] args) {
        RealService proxyService=getProxy(RealService.class);
        proxyService.sayHello();
    }

}